package com.atguigu.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Author zhangchunsheng
 * @CreateTime: 2025/01/08
 */
public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求[功能:登录或注册]
        String requestURI = request.getRequestURI();
        String[] split = requestURI.split("/");
        String methodName = split[split.length - 1];
        try {
            //前提:methodName 必须和被调用的方法名一致
            //通过反射原理,动态调用方法
            Method methodObj = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //设置权限
            methodObj.setAccessible(true);
            //调用方法
            methodObj.invoke(this,request,response);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
}
